
const { getProperty, assert, each, setDeepProperty } = require("../../../lib/tools")

function addLogic(entry,controller,{ cfg}){
    const entryName = getProperty(entry,e=>e.base.entryClassName)
    assert(entryName,"entryName is null")
    const con = getProperty(controller,c=>c[entryName],undefined)
    assert(con,`${entryName} 's controller is null`)

    // const cfg = getProperty(methods,m=>m[methodName].controller)
    assert(cfg,"methods config is null!")

    const ctx = {
        entryName
        , entry
        , getProperty
    }

    cfg.imports.forEach(im=>{
        if(im.type && im.type==='function'){
            const func = new Function(...im.args)
            func.bind(ctx)
            con.imports.push(func(ctx))
        }else{
            con.imports.push(im)
        }
    })

   

    const method = {}
    if(cfg.method){
        each(cfg.method,(config,key)=>{
            if(config.type && config.type==='function'){
                const func = new Function(...config.args)
                func.bind(ctx)
                method[key] = func(ctx)
            } else {
                method[key] = config
            }
        })
    }
    

    const funcs = getProperty(cfg,c=>c.functions)
    if(funcs && funcs.length){
        funcs.forEach(fun=>{
            const f = new Function(...fun.logic)
            setDeepProperty(method,fun.path, fun.key, f(ctx))
        })
        
    }

    con.methods.push(method)
    
}

module.exports = {
    addLogic
}